package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.mapper.CheckGroupMapper;
import com.itheima.mapper.CheckItemMapper;
import com.itheima.mapper.SetmealMapper;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {
    @Autowired
    private SetmealMapper setmealMapper;
    @Autowired
    private CheckItemMapper checkItemMapper;
    @Autowired
    private CheckGroupMapper checkGroupMapper;

    @Autowired
    private JedisPool jedisPool;

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")   //从属性文件中读取要生成的html对应的目录
    private String outPutPath;

    //添加套餐功能
    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //新增套餐
        setmealMapper.add(setmeal);
        //关联套餐和检查组的关联关系
        setmealIdAndCheckgroupId(setmeal, checkgroupIds);

        //将图片名称存入redis中
        savePicToRedis(setmeal.getImg());

        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list) {
        Map map = new HashMap();

        //为模板提供数据,生成静态页面
        map.put("setmealList", list);

        generateHtml("mobile_setmeal.ftl", "m_setmeal.html", map);
    }


    //生成当前方法所需要的静态页面
    public void generateMobileStaticHtml() {
        //准备模板文件中所需要的数据
        List<Setmeal> setmealList = getAllSetmeal();
        //生成套餐列表静态页面
        generateMobileSetmealListHtml(setmealList);
        //生成套餐详情静态页面
        generateMobileSetmealDetailHtml(setmealList);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list) {
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal", setmealMapper.findById(setmeal.getId()));
            //每个套餐生成一个套餐详情静态页面
            generateHtml("mobile_setmeal_detail.ftl", "setmeal_detail_" + setmeal.getId() + ".html", map);
        }
    }


    //通用的方法，用于生成静态页面
    public void generateHtml(String templateName, String htmlPageName, Map<String, Object> dataMap) {
        //1.创建配置类
        Configuration configuration = freeMarkerConfigurer.getConfiguration();
        //2.输出流
        Writer out = null;

        try {
            //加载模板文件
            Template template = configuration.getTemplate(templateName);
            //生成数据
            File file = new File(outPutPath + "\\" + htmlPageName);
            //输出流输出文件
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            template.process(dataMap, out);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    //将图片名称存入redis中
    private void savePicToRedis(String pic) {
        Jedis resource = jedisPool.getResource();
        resource.sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES, pic);
        resource.close();
    }

    //建立套餐和检查组的多对多关系
    public void setmealIdAndCheckgroupId(Setmeal setmeal, Integer[] checkgroupIds) {
        Integer id = setmeal.getId();
        Map<String, Integer> map = new HashMap<>();
        //遍历数组
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                map.put("checkgroupId", checkgroupId);
                map.put("setmealId", id);
                setmealMapper.setmealIdAndCheckgroupId(map);
            }
        }
    }

    //分页查询
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //分页插件分页
        PageHelper.startPage(currentPage, pageSize);

        Page<Setmeal> page = setmealMapper.findPage(queryString);
        long total = page.getTotal();
        List<Setmeal> list = page.getResult();
        return new PageResult(total, list);
    }

    //根据套餐id查询对应套餐数据
    @Override
    public Setmeal findById(Integer setmealId) {
        //通配置文件sql多对多关联查询语句来实现查询
        return setmealMapper.findById(setmealId);

   /*     //通过java代码实现多对多查询
        Setmeal setmeal = setmealMapper.findById(setmealId);
        List<CheckGroup> checkGroupsList = new ArrayList<>();

        // List<CheckGroup> checkGroupsList = setmeal.getCheckGroups();


        //查询中间表获取套餐对应的所有检查组Id
        List<Integer> checkIdList = setmealMapper.findcheckgroupIdsBysetmealId(setmealId);
        //遍历检查组Id集合,查询获取该套餐对应的所有检查组
        for (Integer checkId : checkIdList) {
            CheckGroup checkGroup = checkGroupMapper.findById(checkId);

            List<Integer> checkitemIdsByCheckgroupIdList = checkGroupMapper.findCheckitemIdsByCheckgroupId(checkGroup.getId());

            List<CheckItem> checkItemsList = new ArrayList<>();

            //遍历该检查组对应的检查项Id
            for (Integer checkItemId : checkitemIdsByCheckgroupIdList) {
                //根据检查项id查询检查项
                CheckItem checkItem = checkItemMapper.findById(checkItemId);
                //将该检查项添加到集合中
                checkItemsList.add(checkItem);
            }
            //将获取到的检查项添加到检查组属性中
            checkGroup.setCheckItems(checkItemsList);

            checkGroupsList.add(checkGroup);
        }

        //将获取到的检查组集合添加到套餐的属性中
        setmeal.setCheckGroups(checkGroupsList);
        //返回套餐
        return setmeal;*/
    }

    //根据套餐id查询单个套餐信息
    public Setmeal findOne(Integer setmealId){
        return setmealMapper.findOne(setmealId);
    }

    //根据套餐id查询关联的检查组,多对多关联关系
    @Override
    public List<Integer> findcheckgroupIdsBysetmealId(Integer setmealId) {
        return setmealMapper.findcheckgroupIdsBysetmealId(setmealId);
    }

    //编辑套餐
    @Override
    public void edit(Setmeal setmeal, Integer[] checkgroupIds) {
        //获取该套餐原有图片的名称
        Setmeal findSetmeal = setmealMapper.findById(setmeal.getId());

        //1.编辑套餐
        setmealMapper.edit(setmeal);

        //2.删除套餐和检查组的关联关系
        setmealMapper.deleteBysetmealId(setmeal.getId());

        //3.重新建立套餐和检查组的关联关系
        setmealIdAndCheckgroupId(setmeal, checkgroupIds);

        //4.向redis数据库中添加已成功上传的图片名称
        savePicToRedis(setmeal.getImg());
        //5.redis数据库中删除原先保存的套餐图片名称
        Jedis resource = jedisPool.getResource();
        resource.srem(RedisConstant.SETMEAL_PIC_DB_RESOURCES, findSetmeal.getImg());
        //6. 释放资源!!!重要!!!
        resource.close();

    }

    //删除功能
    @Override
    public void delete(Integer setmealId) {
        //1.删除中间表的套餐 关联检查组
        setmealMapper.deleteBysetmealId(setmealId);

        //2.删除套餐表中的套餐数据
        setmealMapper.delete(setmealId);
    }


    //获取所有套餐方法
    @Override
    public List<Setmeal> getAllSetmeal() {
        return setmealMapper.getAllSetmeal();
    }


}
